from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.db.models import Count, Q
from django.utils import timezone
from datetime import timedelta
from .models import HostStatistics
from .serializers import HostStatisticsSerializer
from hosts.models import Host


class HostStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
    """主机统计视图集"""
    queryset = HostStatistics.objects.all()
    serializer_class = HostStatisticsSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        queryset = HostStatistics.objects.all()
        stat_date = self.request.query_params.get('stat_date', None)
        stat_type = self.request.query_params.get('stat_type', None)
        city_name = self.request.query_params.get('city_name', None)
        
        if stat_date:
            queryset = queryset.filter(stat_date=stat_date)
        if stat_type:
            queryset = queryset.filter(stat_type=stat_type)
        if city_name:
            queryset = queryset.filter(city_name__icontains=city_name)
            
        return queryset
    
    @action(detail=False, methods=['get'])
    def current_stats(self, request):
        """获取当前主机统计信息"""
        try:
            # 获取当前主机统计
            total_hosts = Host.objects.count()
            online_hosts = Host.objects.filter(status='online').count()
            offline_hosts = Host.objects.filter(status='offline').count()
            maintenance_hosts = Host.objects.filter(status='maintenance').count()
            
            # 按城市统计
            city_stats = []
            from hosts.models import City
            cities = City.objects.all()
            for city in cities:
                city_host_count = Host.objects.filter(data_center__city=city).count()
                city_stats.append({
                    'city_name': city.name,
                    'city_code': city.code,
                    'host_count': city_host_count
                })
            
            # 按机房统计
            datacenter_stats = []
            from hosts.models import DataCenter
            datacenters = DataCenter.objects.all()
            for dc in datacenters:
                dc_host_count = Host.objects.filter(data_center=dc).count()
                datacenter_stats.append({
                    'datacenter_name': dc.name,
                    'city_name': dc.city.name,
                    'host_count': dc_host_count
                })
            
            return Response({
                'total_hosts': total_hosts,
                'online_hosts': online_hosts,
                'offline_hosts': offline_hosts,
                'maintenance_hosts': maintenance_hosts,
                'city_stats': city_stats,
                'datacenter_stats': datacenter_stats,
                'generated_at': timezone.now()
            })
            
        except Exception as e:
            return Response({'error': f'获取统计信息失败: {str(e)}'}, status=500)
    
    @action(detail=False, methods=['get'])
    def daily_summary(self, request):
        """获取每日统计摘要"""
        try:
            # 获取最近7天的统计
            end_date = timezone.now().date()
            start_date = end_date - timedelta(days=7)
            
            daily_stats = HostStatistics.objects.filter(
                stat_date__gte=start_date,
                stat_date__lte=end_date
            ).order_by('stat_date')
            
            return Response({
                'daily_stats': HostStatisticsSerializer(daily_stats, many=True).data,
                'period': {
                    'start_date': start_date,
                    'end_date': end_date
                }
            })
            
        except Exception as e:
            return Response({'error': f'获取每日统计失败: {str(e)}'}, status=500)
